import axios from 'axios'
import {
  Message
} from 'element-ui'
import store from '../store'
import {
  getToken
} from '@/utils/auth'

// 创建axios实例
const service = axios.create({
  responseType: 'json',
  // 响应构造器
  transformResponse: [
    function(data) {
      return data
    }
  ],
  baseURL: process.env.BASE_API, // api 的 base_url
  timeout: 15000 // 请求超时时间
})

// request拦截器
service.interceptors.request.use(
  config => {
    if (store.getters.token) {
      // 让每个请求携带自定义token 请根据实际情况自行修改
      config.headers.Authorization = 'Bearer ' + getToken()
    }
    return config
  },
  error => {
    // Do something with request error
    // console.log(error) // for debug
    Promise.reject(error)
  }
)

// response 拦截器
service.interceptors.response.use(
  response => {
    if (response.config.responseType === 'blob') {
      return Promise.resolve(response.data)
    } else {
      return Promise.resolve(response.data)
    }
  },
  error => {
    // console.log('err' + error) // for debug
    if (error.response && error.response.status === 401) {
      store.dispatch('FedLogOut')
      location.reload() // 为了重新实例化vue-router对象 避免bug
    } else {
      Message({
        message: error.response.data.message,
        type: 'error',
        duration: 3 * 1000
      })
    }
    return Promise.reject(error.response.data)
  }
)

export default service
